import { Component, OnInit, Input } from '@angular/core';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { RemarksContentComponent } from "../remarks-content/remarks-content.component";
import { AlertController } from '@ionic/angular';
import { ModalController } from "@ionic/angular";
import { ActionSheetService } from "ng-zorro-antd-mobile";
declare let $: any;
@Component({
  selector: 'app-presales-business-opt',
  templateUrl: './presales-business-opt.component.html',
  styleUrls: ['./presales-business-opt.component.scss'],
})
export class PresalesBusinessOptComponent implements OnInit {

  constructor(
    private alert: AlertController,
    private http: HttpService,
    private appGlobalService: AppGlobalService,
    private eventService: EventService,
    public modalController: ModalController
  ) { }
  @Input() tagData: any;
  isshowhistory = false;   // 判断展示还是隐藏
  sessionId: string;
  receiveList: any;
  isDataShow = false;
  ifget: any;
  foldimg: any;
  pageSize: 0;
  foldimgId = 'foldimgId';
  panelId = 'id-presales-history-panel';
  optBtnArray = [];
  otherOptBtnArray = [];
  ngOnInit() {
    try {
      this.panelId += new Date().getTime();
      this.foldimgId += new Date().getTime();
      this.tagData.data.display = {

        style: "1",

        content: this.tagData.data.DownDiv[0].title.label === undefined ?
          this.tagData.data.DownDiv[0].title :
          this.tagData.data.DownDiv[0].title.label,
        cssStyle:
          this.tagData.data.DownDiv[0].cssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].cssStyle,

        status3CssStyle: // status3
          this.tagData.data.DownDiv[0].status3CssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].status3CssStyle,

        statusLeftCssStyle: // statusLeftCssStyle
          this.tagData.data.DownDiv[0].statusLeftCssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].statusLeftCssStyle,

        statusBox1CssStyle: // statusBox1CssStyle
          this.tagData.data.DownDiv[0].statusBox1CssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].statusBox1CssStyle,

        titleCssStyle: // 标题样式
          this.tagData.data.DownDiv[0].titleCssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].titleCssStyle,

        circleCssStyle: // 圆环样式
          this.tagData.data.DownDiv[0].circleCssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].circleCssStyle,

        circle1CssStyle: // 圆环1样式
          this.tagData.data.DownDiv[0].circle1CssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].circle1CssStyle,

        foldImgCssStyle: // 图标
          this.tagData.data.DownDiv[0].foldImgCssStyle === undefined ? null :
            this.tagData.data.DownDiv[0].foldImgCssStyle,

        arrowUpImg: // 图标地址
          this.tagData.data.DownDiv[0].arrowUpImg === undefined ? null :
            this.tagData.data.DownDiv[0].arrowUpImg
      };
      if (this.tagData.data.DownDiv[0]) {

        const optArray = Object.keys(this.tagData.data.DownDiv[0]);

        if (this.tagData.data.DownDiv[0].opt) {
          if (this.tagData.data.DownDiv[0].opt.formData !== undefined) {
            this.tagData.data.button = {
              visible: true,
              submit: this.tagData.data.DownDiv[0].opt.submit ? this.tagData.data.DownDiv[0].opt.submit : null,
              link: this.tagData.data.DownDiv[0].opt.link ? this.tagData.data.DownDiv[0].opt.link : null,
              label: this.tagData.data.DownDiv[0].opt.label,
              type: "" // this.tagData.data.DownDiv[0].opt.label === '领取' ? "service" : ""
            };
            this.tagData.data.button = Object.assign(this.tagData.data.button, this.tagData.data.DownDiv[0].opt);
          } else {
            // TODO 新增数组用于按钮列表
            // Object.keys(this.tagData.data.DownDiv[0]).forEach(v => {
            //   console.log('v===', v);
            // });
            this.tagData.data.button = {
              visible: true,
              submit: this.tagData.data.DownDiv[0].opt.submit ? this.tagData.data.DownDiv[0].opt.submit : null,
              link: this.tagData.data.DownDiv[0].opt.link ? this.tagData.data.DownDiv[0].opt.link : null,
              label: this.tagData.data.DownDiv[0].opt.label,
              type: "" // this.tagData.data.DownDiv[0].opt.label === '领取' ? "service" : ""
            };
          }

        }
        if (this.tagData.data.DownDiv[0].secondOpt) {
          this.tagData.data.secondButton = {
            visible: true,
            submit: this.tagData.data.DownDiv[0].secondOpt.submit ? this.tagData.data.DownDiv[0].secondOpt.submit : null,
            link: this.tagData.data.DownDiv[0].secondOpt.link ? this.tagData.data.DownDiv[0].secondOpt.link : null,
            label: this.tagData.data.DownDiv[0].secondOpt.label,
            type: "" // this.tagData.data.DownDiv[0].opt.label === '领取' ? "service" : ""
          };
        }

        // 蜂喔商户1.6.18新增
        if (optArray && optArray.length > 0) {
          optArray.forEach(item => {
            if (item.includes('opt_')) {
              // tslint:disable-next-line:no-string-literal
              this.tagData.data.DownDiv[0][item]['visible'] = true;
              // tslint:disable-next-line:no-string-literal
              this.tagData.data.DownDiv[0][item]['type'] = '';
              this.optBtnArray.push(this.tagData.data.DownDiv[0][item]);
            }
          });
        }
        if (this.tagData.data.button === undefined && this.optBtnArray.length > 0) {
          this.tagData.data.button = { visible: true, type: "" };
          const first = this.optBtnArray.shift();
          this.otherOptBtnArray = this.optBtnArray;
          this.tagData.data.button = Object.assign(this.tagData.data.button, first);
        }
      }

      this.tagData.data.expand = [];
      const len = this.tagData.data.DownDiv.length;
      if (len === 1) {
        if (this.tagData.data.DownDiv[0] && !this.tagData.data.DownDiv[0].opt) {
          if (this.tagData.data.DownDiv[0].rightLabel) {
            this.tagData.data.expand = {};
            this.tagData.data.display.rightLabel = this.tagData.data.DownDiv[0].rightLabel;
          } else if (this.tagData.data.display) {

          } else {
            this.tagData.data.display = null;
            this.tagData.data.expand.push(
              {
                style: "1",
                content:
                  this.tagData.data.DownDiv[0].title.label ?
                    this.tagData.data.DownDiv[0].title.label :
                    this.tagData.data.DownDiv[0].title
              });
          }
        }
      } else {
        for (let i = 1; i < len; i++) {
          const subData = this.tagData.data.DownDiv[i];
          this.tagData.data.expand.push({ style: "1", content: subData.title.label ? subData.title.label : subData.title });
        }
      }

      this.sessionId = localStorage.getItem('sessionId');

      this.foldimg = "../../../assets/img/folddown.png";




      if (this.tagData.data.display) {
        this.ifget = true;
      } else {
        this.ifget = false;
      }


      if (this.isDataShow === true) {
        this.foldimg = "../../../assets/img/foldup.png";
      } else {
        this.foldimg = "../../../assets/img/folddown.png";
      }



      // 
      if (this.tagData.data.display && this.tagData.data.display.arrowUpImg) {
        this.foldimg = this.tagData.data.display.arrowUpImg;
      }



    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  // 业务备注->填写备注弹框
  async presentModal(value, opt) {
    opt.submit.content.remark_class = "1";
    opt.submit.content.remark_text = "";
    opt.submit.content.remark_type = "0";
    const remarkIcon = {
      iconName: "assets/img/List_operation_icon_bz@3x.png",
      formData: {
        button: {
          label: "确定",
          submit: opt.submit
        },
        textarea: opt.textarea
      }
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { tagData: { data: { data: [] } }, item: remarkIcon, type: value, pageSize: this.pageSize }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  warningClick(opt) {
    if (opt.textarea !== undefined && opt.textarea !== null) {
      this.presentModal('remarks', opt);
    } else if (opt.formData !== undefined && opt.formData !== null) {
      this.showActionSheet(opt.formData);
    } else if (opt.submit !== undefined && opt.submit !== null) {
      const params = {
        content: opt.submit.content,
        id: opt.submit.id,
        sessionId: this.sessionId
      };
      this.http.post('application/submit', params, res => {
        // 请求数据成功
        if (res.success === true) {
          this.appGlobalService.showToast(res.message, 2000, 'middle');
          this.appGlobalService.reloadCurrentPage();
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
      });
    } else if (opt.link !== undefined && opt.link !== null) {
      const subParams = {
        pageId: opt.link.target,
        params: opt.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(subParams);
    }

  }


  operationclick(obj) {
    if (obj.type === "service") {
      this.cancel();
    } else {

      if (obj.formData !== undefined && obj.formData !== null) {
        this.showActionSheet(obj.formData);
        // 请求获取新数据
      } else if (obj.submit !== undefined && obj.submit !== null) {
        const params = {
          content: obj.submit.content,
          id: obj.submit.id,
          sessionId: this.sessionId
        };
        this.http.post('application/submit', params, res => {
          // 请求数据成功
          if (res.success === true) {
            this.tagData.data.expand = res.data.expand;
            this.ifget = false;
            this.appGlobalService.showToast(res.message, 2000, 'middle');
            this.appGlobalService.reloadCurrentPage();
          } else {
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
            /* localStorage.setItem('needRefresh', 'true'); */
          }
        });
      } else if (obj.link !== undefined && obj.link !== null) {
        const subParams = {
          pageId: obj.link.target,
          params: obj.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(subParams);
      }

    }
  }

  showclick() {

    this.isshowhistory = !this.isshowhistory;
    // const h = $(window).scrollTop();
    if (this.isshowhistory === true) {
      // this.foldimg = "../../../assets/img/foldup.png";
      // $('#id-presales-history-panel').fadeIn();
      // $('#id-presales-history-panel').animate({ height: "auto" });
      // $("#id-presales-history-panel").slideDown();
      if (this.tagData.data.display && this.tagData.data.display.arrowUpImg) {
        $("#" + this.foldimgId).css('transform', 'rotate(180deg)');
      } else {
        $("#" + this.foldimgId).attr("src", "../../../assets/img/foldup.png");
      }
      $("#" + this.panelId).slideToggle("slow");
      // $('html,body').animate({ "scrollTop": h + 800 }, 800);
      // localStorage.setItem('nav1ScrollToBottomTag', '50');
      // this.eventService.eventEmit.emit('nav1ScrollToBottom', '1');
    } else {
      // $('#id-presales-history-panel').fadeOut();
      // $("#id-presales-history-panel").slideUp();
      if (this.tagData.data.display && this.tagData.data.display.arrowUpImg) {
        $("#" + this.foldimgId).css('transform', 'rotate(0deg)');
      } else {
        $("#" + this.foldimgId).attr("src", "../../../assets/img/folddown.png");
      }
      $("#" + this.panelId).slideToggle("slow");
      // $('html,body').animate({ "scrollTop": h + 800 }, 800);
      // localStorage.setItem('nav1ScrollToBottomTag', '50');
      // this.eventService.eventEmit.emit('nav1ScrollToBottom', '1');
      // this.foldimg = "../../../assets/img/folddown.png";
    }
    // console.log(this.isshowhistory);
  }
  onReceiveChange(index) {
    if (index === 0) {
      this.isDataShow = !this.isDataShow;
      if (this.isDataShow === true) {
        this.foldimg = "../../../assets/img/foldup.png";
      } else {
        this.foldimg = "../../../assets/img/folddown.png";
      }
    }
  }
  async cancel() {
    const content = this.tagData.data.button.submit.content;
    const listId = this.tagData.data.button.submit.id;
    const params = {
      content,
      id: listId,
      sessionId: this.sessionId
    };
    const tip = "领取后不能自行放弃，确定要领取服务吗？";
    const alert = await this.alert.create({
      message: tip,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
          }
        }, {
          text: '确定',
          cssClass: 'LJ',
          handler: () => {
            this.http.post('application/submit', params, res => {
              // 请求数据成功
              if (res.success === true) {
                this.tagData.data.expand = res.data.expand;
                this.ifget = false;
                this.appGlobalService.showToast(res.message, 2000, 'middle');
                this.appGlobalService.reloadCurrentPage();
              } else {
                // 请求数据失败
                this.appGlobalService.showToast(res.message, 2000, 'middle');
                /* localStorage.setItem('needRefresh', 'true'); */
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }
  /*//备份
  operationclick() {
      let content = this.tagData.data.button.submit.content;
      let listId = this.tagData.data.button.submit.id;
      const params = {
        content,
        id: listId,
        sessionId: this.sessionId
      };
      // 请求获取新数据
      this.http.post('application/submit', params, res => {
        // 请求数据成功
        if ( res['success'] === true) {
          this.tagData.data.expand = res.data.expand;
          this.ifget = false;
          this.appGlobalService.showToast(res['message'], 2000, 'middle');
          this.tabsService.reloadCurrentPage();
          setTimeout(() => {
            localStorage.setItem('needRefresh','true');
          }, 2000);
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res['message'], 2000, 'middle');
          localStorage.setItem('needRefresh','true');
        }
      });
    }
   */

  getNgStyle(str) {
    try {
      return JSON.parse(str);
    } catch (error) {
      return {};
    }
  }

  getYuqnQuan(str) {
    try {
      return {
        background: JSON.parse(str).color,
        border: '1px solid ' + JSON.parse(str).color,
        color: JSON.parse(str).color,
        height: '10px',
        width: '10px'
      };
    } catch (error) {
      return {
        background: '#6ccb59',
        color: JSON.parse(str).color,
        border: '1px solid #76cb4e',
        height: '10px',
        width: '10px'
      };
    }
  }


  // 业务备注->备注列表弹框
  showActionSheet = (formData) => {
    const buttons = formData.map(
      obj => obj.label
    );
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons
      },
      buttonIndex => {
        console.log(buttonIndex);
        if (buttonIndex >= 0) {
          this.go(
            formData[buttonIndex]
          );
        }
      }
    );
  }

  go(item) {
    if (item.link.type === "url") {
      // window.open(item.link.url);
      // 修复禅道bug 3676 add by andrew.wen 
      this.appGlobalService.openUrl('', item.link.url);
    } else {
      const params = {
        pageId: item.link.target,
        params: item.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(params);
    }
  }
}
